package com.FH.applyFrom.car;

import com.FH.applyForm.officeServies.carManage.CarPullDTO;
import com.FH.applyForm.officeServies.carManage.CarResource;
import com.FH.applyForm.officeServies.carManage_firstType.CarManageResource;
import com.FH.applyForm.officeServies.carManage_secondType.CarManagesResource;
import com.FH.applyForm.officeServies.carManage_secondType.CarManagesShowDTO;
import com.FH.organization.operator_log.OperatorLogPullDTO;
import com.FH.organization.operator_log.OperatorLogResource;
import com.FH.organization.people.KamMemberResource;
import com.FH.organization.remind.RemindPullDTO;
import com.FH.organization.remind.RemindResource;
import com.FH.organization.suggestion.SuggestionResource;
import com.FH.organization.work_flow.WorkFlowPullDTO;
import com.FH.organization.work_flow.WorkFlowResource;
import com.FH.util.AccessDB;
import com.FH.util.ResultDTO;
import com.FH.util.warnSrc;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.Stateless;
import javax.inject.Inject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by acer on 2016/7/14.
 * 车辆管理实现类
 */
@Stateless
public class CarmanagerDAOImpl extends AccessDB implements CarmanagerDAO{
    /**
     * 查询车辆管理信息
     * @param
     * @return
     */


    @Inject
    OperatorLogResource  operatorLogResource;
    @Inject
    WorkFlowResource workFlowResource;
    @Inject
    CarmanagerResource carmanagerResource;
    @Inject
    CarResource carResource;
    @Inject
    KamMemberResource kamMemberResource;
    @Inject
    CarManagesResource carManagesResource;
    @Inject
    CarManageResource carManageResource;
    @Inject
    RemindResource remindResource;
    @Inject
    SuggestionResource suggestionResource;

    public ResultDTO getCarmanagerInfo(String search, String page, String size){

        ResultDTO resultDTO = new ResultDTO();
        try {
            JSONObject json = new JSONObject(search);
            String existName = "0";

            String sqlexit = "select count(1) from car_manage where 1=1 ";

            String sql_w ="";//查询条件sql组合

            String sql_page = "";//分页sql组合
            Integer page_ok = Integer.parseInt(page);
            Integer size_ok = Integer.parseInt(size);
            if(page.equals("1")){
                sql_page = " limit 0,"+size+"";
            }else{
                sql_page = " limit "+((page_ok-1)*size_ok)+","+size+"";
            }

            if(json.has("isverify")){
                sql_w += " AND isverify ='" + json.getString("isverify")+"'";
            }
//            else{
//                sql_w += " AND (isverify IS NULL OR isverify=0)";
//            }


            if(json.has("car_manage_id")){
                sql_w += " AND car_manage_id = '"+json.getString("car_manage_id")+"'";
            }
            if(json.has("member_id")){
                sql_w += " AND member_id ='"+json.getString("member_id")+"'";
            }
            String sql_ok = sqlexit+sql_w ;//组合好的sql语句
            existName = getReportingToOne(sql_ok);

            List<String []> seresult = new ArrayList<String []>();

            List<CarmanagerShowDTO> result = new ArrayList<CarmanagerShowDTO>();
            if (!existName.equals("0")){
                String sql="select car_manage_id,member_id,isverify,carsecond_id,car_managetype,car_borrow_people,car_usertime," +
                        "car_backtime,car_manage_addr,car_manage_kilometers,car_manage_direct,car_manage_reason,is_warn,fail_resource from car_manage where 1=1 "+sql_w +" ORDER BY car_usertime DESC"+sql_page ;
                seresult = this.getReportingTo(sql);

                //构建返回对象
                for (int i = 0; i < seresult.size(); i++){

                    CarmanagerShowDTO carmanager=new CarmanagerShowDTO();
                    carmanager.setCar_manage_id(seresult.get(i)[1]);
                    carmanager.setMember_id(seresult.get(i)[2]);
                    carmanager.setIsverify(seresult.get(i)[3]);
                    carmanager.setCarsecond_id(seresult.get(i)[4]);
                    carmanager.setCar_managetype(seresult.get(i)[5]);
                    carmanager.setCar_borrow_people(seresult.get(i)[6]);
                    carmanager.setCar_usertime(seresult.get(i)[7]);
                    carmanager.setCar_backtime(seresult.get(i)[8]);
                    carmanager.setCar_manage_addr(seresult.get(i)[9]);
                    carmanager.setCar_manage_kilometers(seresult.get(i)[10]);
                    carmanager.setCar_manage_direct(seresult.get(i)[11]);
                    carmanager.setCar_manage_reason(seresult.get(i)[12]);
                    carmanager.setIs_warn(seresult.get(i)[13]);
                    carmanager.setFail_resource(seresult.get(i)[14]);
                    ResultDTO worklist=null,userlist=null,suggestion=null,borrow_people,secondr,derectlist;

                    if(json.has("isverify")){
                       String state=json.getString("isverify");
                        worklist=workFlowResource.getWorkFlowInfo("{work_flow_formid:"+seresult.get(i)[1]+",work_flow_state:"+state+"}","1","20");
                    }else{
                        worklist=workFlowResource.getWorkFlowInfo("{work_flow_formid:"+seresult.get(i)[1]+"}","1","20");
                    }
                    //流程信息
                    carmanager.setResult(worklist.getValues());
                    //随行人员信息
                    userlist = carResource.getCarInfo("{car_manage_id:"+seresult.get(i)[1]+"}","1","1000");
                    carmanager.setQq(userlist.getValues());

                    //借车人信息
                    borrow_people=kamMemberResource.getUserListInfo("{member_id:"+seresult.get(i)[6]+"}","1","1000");
                    carmanager.setBorrowlist(borrow_people.getValues());

                     //调度员信息
                    derectlist=kamMemberResource.getUserListInfo("{member_id:"+seresult.get(i)[11]+"}","1","1000");
                    carmanager.setDirectlist(derectlist.getValues());
                    //车牌号信息
                    secondr=carManagesResource.getCarManagesInfo("{carsecond_id:"+seresult.get(i)[4]+"}","1","1000");
                    carmanager.setSelcond(secondr.getValues());

                    ResultDTO fistmenu=null;
                    fistmenu=carManageResource.getCarManageInfo("{carfirst_id:"+((CarManagesShowDTO)secondr.getValues().get(0)).getCarfirst_id()+"}","1","1000");
                    carmanager.setFirstmene(fistmenu.getValues());

                    if(seresult.get(i)[1] != null && ! seresult.get(i)[1].equals("")){

                        suggestion=suggestionResource.getSuggestionInfo("{form_id:" + seresult.get(i)[1] + "}", "1", "100");
                        carmanager.setSuggestionShowDTOs(suggestion.getValues());
                    }
                    result.add(carmanager);

                }
            }
            if(seresult.size()!=0) {
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.get_success);
                //获取上报人



            }else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
            }
            resultDTO.setStr(result.size()+"");
            resultDTO.setValues(result);

        }catch (JSONException e){
            e.printStackTrace();
        }
        return resultDTO;


    }
    /**
     * 增加车辆管理信息
     * @param carmanagerPullDTO
     * @return
     */
    public ResultDTO addCarmanagerInfo(CarmanagerPullDTO  carmanagerPullDTO) {
        //  String sql_isHas = "select count(1) from car_manager WHERE member_id='"+carmanagerPullDTO.getMember_id()+"'";

        //  String existCarmanage= getReportingToOne(sql_isHas);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        int resultls = 0;

        String existName = "";
        /**
         * 判断申请单中是否已存在此数据
         *
         * 若存在  进行更新
         *
         * 如不存在 执行add方法
         *
         */
        String car_manage_id = carmanagerPullDTO.getCar_manage_id();
        if (car_manage_id != null && !car_manage_id.equals("")) {

            String sql = "select count(1) from car_manage where car_manage_id='" + carmanagerPullDTO.getCar_manage_id() + "'";

            existName = getReportingToOne(sql);

            if (!existName.equals("0")) {
                return carmanagerResource.updateCarmanagerInfo(carmanagerPullDTO);
            }
        }

        //构建返回对象
        ResultDTO resultDTO = new ResultDTO();
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        //拿到车的id，判断此车在某时间段内是否被借用
        String carsecond_id = carmanagerPullDTO.getCarsecond_id();
        if (carsecond_id != null && !carsecond_id.equals("")) {
            carmanagerPullDTO.getCarsecond_id();


            String sql = "select count(1) from car_manage where ((car_backtime <= '" + carmanagerPullDTO.getCar_backtime() + "') and (car_usertime>='" + carmanagerPullDTO.getCar_usertime() + "')) AND  carsecond_id =  '" + carmanagerPullDTO.getCarsecond_id() + "' ";

            String existone = getReportingToOne(sql);


            if (!existone.equals("0")) {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion("车辆被占用");

                return resultDTO;
            }
        }

        //if(existCarmanage.equals("0")){

        String carmanager_insert = "";
        carmanager_insert += "insert into car_manage (car_manage_id,member_id,isverify,fail_resource,carsecond_id,car_usertime," +
                "car_backtime,car_manage_addr,car_manage_kilometers,car_manage_direct,car_manage_reason,car_borrow_people,is_warn)" +
                "values('" + uuid + "','" + carmanagerPullDTO.getMember_id() + "','" + 0 + "','" + " " + "','" + carmanagerPullDTO.getCarsecond_id() + "'" +
                ",'" + carmanagerPullDTO.getCar_usertime() + "','" + carmanagerPullDTO.getCar_backtime() + "','" + carmanagerPullDTO.getCar_manage_addr() + "','" + carmanagerPullDTO.getCar_manage_kilometers() + "'" +
                ",'" + carmanagerPullDTO.getCar_manage_direct() + "','" + carmanagerPullDTO.getCar_manage_reason() + "','" + carmanagerPullDTO.getCar_borrow_people() + "','" + carmanagerPullDTO.getIs_warn() + "')";
        //插入业务表
        resultls = addReportingTo(carmanager_insert);

        //}
        if (resultls != 0) {
            resultDTO.setStr(uuid);
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.add_success);

            /**
             * JSON解析集合、参会人
             */
            if (null != carmanagerPullDTO.getCartype() && !"".equals(carmanagerPullDTO.getCartype())) {
                String cartype = carmanagerPullDTO.getCartype();
                try {
                    JSONArray array = new JSONArray(cartype);
                    if (array != null && array.length() > 0) {
                        List<CarmanagerPullDTO> results = new ArrayList<CarmanagerPullDTO>();
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject jsonObject = array.getJSONObject(i);
                            String id = jsonObject.getString("id");
                            String name = jsonObject.getString("name");
                            CarPullDTO carPullDTO = new CarPullDTO();
                            carPullDTO.setCar_manage_id(uuid);
                            carPullDTO.setMember_id(id);
                            carPullDTO.setName(name);
                            carResource.addCarInfo(carPullDTO);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }


            //日志操作
            OperatorLogPullDTO operatorlogPullDTO = new OperatorLogPullDTO();
            operatorlogPullDTO.setWork_form_id(uuid);
            operatorlogPullDTO.setOperator_log_type("车辆申请");
            operatorlogPullDTO.setOperator_log_title(carmanagerPullDTO.getCar_manage_addr());
            operatorlogPullDTO.setOperator_log_content(carmanagerPullDTO.getCar_manage_reason());
            operatorlogPullDTO.setMember_id(carmanagerPullDTO.getMember_id());
            operatorLogResource.addOperatorLogInfo(operatorlogPullDTO);
            //流程上报

            WorkFlowPullDTO workFlowPullDTO = new WorkFlowPullDTO();
            workFlowPullDTO.setWork_flow_formid(uuid);
            workFlowPullDTO.setWork_flow_type("car_manage");
            workFlowPullDTO.setWork_flow_desc("车辆申请请求审批");
            workFlowPullDTO.setWork_flow_date(time);
            workFlowPullDTO.setWork_flow_order("0");
            workFlowPullDTO.setWork_flow_createid(carmanagerPullDTO.getMember_id());
            workFlowPullDTO.setWork_flow_approval(carmanagerPullDTO.getReport_people());
            workFlowPullDTO.setWork_flow_approval_organization_id(carmanagerPullDTO.getWork_flow_approval_organization_id());
            workFlowPullDTO.setFlow_path_id(carmanagerPullDTO.getFlow_path_id());
            workFlowPullDTO.setWork_flow_suggestion("");
            workFlowResource.addWorkFlowInfo(workFlowPullDTO);


            //提醒调度员


            if (carmanagerPullDTO.getIs_warn() != null&&!"".equals(carmanagerPullDTO.getIs_warn()) ) {


                RemindPullDTO remindPullDTO = new RemindPullDTO();
                remindPullDTO.setRemind_content(carmanagerPullDTO.getCar_manage_reason());
                remindPullDTO.setRemind_time(carmanagerPullDTO.getCar_usertime());
                remindPullDTO.setRemind_type("7");
                remindPullDTO.setRemind_form_id(uuid);
                remindPullDTO.setRemind_order("0");
                remindPullDTO.setCreate_time(time);
                remindPullDTO.setRemind_endtime(carmanagerPullDTO.getCar_backtime());
                remindPullDTO.setRemind_member_id(carmanagerPullDTO.getCar_manage_direct());
                remindPullDTO.setRemind_starttime(carmanagerPullDTO.getCar_usertime());
                remindPullDTO.setRemind_descritpion("您有一个车辆申请单正在进行审批，请注意查看！");
                remindResource.addRemindInfo(remindPullDTO);

            }


        }else{
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
        }

        return resultDTO;


    }

    /**
     * 更新车辆管理信息
     * @param carmanagerPullDTO
     * @return
     */
    public ResultDTO updateCarmanagerInfo(CarmanagerPullDTO  carmanagerPullDTO){


        /**
         * 先删除类别表
         *
         * 再进行添加
         */
        ResultDTO resultss = null;
        String car_manage_id = carmanagerPullDTO.getCar_manage_id();
        CarPullDTO carPullDTO=new CarPullDTO();
        carPullDTO.setCar_manage_id(car_manage_id);
        carResource.deleteCarInfo(carPullDTO);
        //  if(resultss!=null){
        if (null != carmanagerPullDTO.getCartype() && !"".equals(carmanagerPullDTO.getCartype())) {
            String financetype = carmanagerPullDTO.getCartype();
            try {
                JSONArray array = new JSONArray(financetype);
                if (array != null && array.length() > 0) {
                    List<CarmanagerPullDTO> result = new ArrayList<CarmanagerPullDTO>();
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject jsonObject = array.getJSONObject(i);
                        String id = jsonObject.getString("id");
                        String name = jsonObject.getString("name");

                        CarPullDTO carPullDTO1 = new CarPullDTO();
                        carPullDTO1.setCar_manage_id(carmanagerPullDTO.getCar_manage_id());
                        carPullDTO1.setMember_id(id);
                        carPullDTO1.setName(name);
                        carResource.addCarInfo(carPullDTO1);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        ResultDTO resultDTO = new ResultDTO();

        String QUERY = "";

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //更新sql语句
        QUERY += "update car_manage set ";
        if(null!=carmanagerPullDTO.getCar_manage_addr()&&!"".equals(carmanagerPullDTO.getCar_manage_addr())){
            QUERY += ",car_manage_addr = '" + carmanagerPullDTO.getCar_manage_addr() + "'";
        }

        if(null!=carmanagerPullDTO.getCar_borrow_people()&&!"".equals(carmanagerPullDTO.getCar_borrow_people())){
            QUERY += ",car_borrow_people ='" + carmanagerPullDTO.getCar_borrow_people() + "'";
        }
        if(null!=carmanagerPullDTO.getIsverify()&&!"".equals(carmanagerPullDTO.getIsverify())){
            QUERY += ",isverify ='" + carmanagerPullDTO.getIsverify() + "'";
        }

        if(null!=carmanagerPullDTO.getCar_usertime()&&!"".equals(carmanagerPullDTO.getCar_usertime())){
            QUERY += ",car_usertime ='" + carmanagerPullDTO.getCar_usertime() + "'";
        }

        if(null!=carmanagerPullDTO.getCar_backtime()&&!"".equals(carmanagerPullDTO.getCar_backtime())){
            QUERY += ",car_backtime ='" + carmanagerPullDTO.getCar_backtime() + "'";
        }

        if(null!=carmanagerPullDTO.getCar_manage_addr()&&!"".equals(carmanagerPullDTO.getCar_manage_addr())){
            QUERY += ",car_manage_addr ='" + carmanagerPullDTO.getCar_manage_addr() + "'";
        }

        if(null!=carmanagerPullDTO.getCar_manage_kilometers()&&!"".equals(carmanagerPullDTO.getCar_manage_kilometers())){
            QUERY += ",car_manage_kilometers ='" + carmanagerPullDTO.getCar_manage_kilometers() + "'";
        }

        if(null!=carmanagerPullDTO.getCar_manage_direct()&&!"".equals(carmanagerPullDTO.getCar_manage_direct())){
            QUERY += ",car_manage_direct ='" + carmanagerPullDTO.getCar_manage_direct() + "'";
        }

        if(null!=carmanagerPullDTO.getCar_manage_reason()&&!"".equals(carmanagerPullDTO.getCar_manage_reason())){
            QUERY += ",car_manage_reason ='" + carmanagerPullDTO.getCar_manage_reason() + "'";
        }
        if(null!=carmanagerPullDTO.getCarsecond_id()&&!"".equals(carmanagerPullDTO.getCarsecond_id())){
            QUERY += ",carsecond_id ='" + carmanagerPullDTO.getCarsecond_id() + "'";
        }

        QUERY += " where car_manage_id = '" + carmanagerPullDTO.getCar_manage_id() + "'";


        int result = this.addReportingTo(QUERY);

        // 判断SQl是否执行成功
        if (result != 0) {
            resultDTO.setStr(carmanagerPullDTO.getCar_manage_id());
            WorkFlowPullDTO workFlowPullDTO=new WorkFlowPullDTO();
            workFlowPullDTO.setWork_flow_formid(carmanagerPullDTO.getCar_manage_id());
            workFlowPullDTO.setIsverify(carmanagerPullDTO.getIsverify());
            workFlowResource.updateWorkFlowInfo(workFlowPullDTO);

            resultDTO.setStatus("90000");//
            resultDTO.setDescritpion(warnSrc.update_success);
        } else {
            resultDTO.setStatus("90001");//
            resultDTO.setDescritpion(warnSrc.update_fail);
        }
        return resultDTO;
    }

    /**
     * 删除管理信息
     * @param carmanagerPullDTO
     * @return
     */
    public ResultDTO deleteCarmanagerInfo(CarmanagerPullDTO  carmanagerPullDTO){

        String sql_isHas = "select count(1) from car_manage WHERE car_manage_id='"+carmanagerPullDTO.getCar_manage_id()+"'";

        String existCarmanage= getReportingToOne(sql_isHas);

        int resultls = 0;

        //构建返回对象
        ResultDTO resultDTO = new ResultDTO();

        if(!existCarmanage.equals("0")){
            String QUERY="";
            QUERY +="delete from car_manage where  car_manage_id='"+carmanagerPullDTO.getCar_manage_id()+"'";
            //更新车辆管理表
            resultls =  this.addReportingTo(QUERY);
        }
        if(resultls!=0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.delete_success);

            CarPullDTO carPullDTO = new CarPullDTO();
            carPullDTO.setCar_manage_id(carmanagerPullDTO.getCar_manage_id());
            carResource.deleteCarInfo(carPullDTO);

            WorkFlowPullDTO workFlowPullDTO=new WorkFlowPullDTO();
            workFlowPullDTO.setWork_flow_formid(carmanagerPullDTO.getCar_manage_id());
            workFlowResource.deleteWorkFlowInfo(workFlowPullDTO);
        }else{
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.delete_fail);
        }

        return resultDTO;

    }
}
